<template>
  <!-- type="flex"让布局参数可用 -->
  <el-row style="width: 100%;margin-top: 10vh;" type="flex" justify="center" align="middle">
    <el-col :span="20">
      <el-row type="flex" align="middle">
        <el-col :span="15">
          <el-row>
            <el-col>
              <video ref="mainVideo" name="main" :class="'mainVideo'" @click="swapVideos($event)" autoplay />
            </el-col>
          </el-row>
        </el-col>
        <el-col :offset="1" :span="8">
          <!-- <el-row v-for="(item, index) in otherVideoList" :key="index"><el-col>
              <video :ref="item" :class="'otherVideo'" @click="swapVideos($event)" autoplay></video>
            </el-col></el-row> -->
          <el-row><el-col>
              <video ref="otherVideo1" :class="'otherVideo'" @click="swapVideos($event)" autoplay></video>
            </el-col></el-row>
          <el-row><el-col>
              <video ref="otherVideo2" :class="'otherVideo'" @click="swapVideos($event)" autoplay></video>
            </el-col></el-row>
          <el-row><el-col>
              <video ref="otherVideo3" :class="'otherVideo'" @click="swapVideos($event)" autoplay></video>
            </el-col></el-row>
        </el-col>
      </el-row>
      <el-row style="width: 100%;margin-top: 10vh;" type="flex" justify="center" align="middle">
        <el-col :span="10">
          <el-button @click="getLocal">开始连接万物</el-button>
        </el-col>
        <el-col :span="10">
          <el-button @click="displayStart">屏幕共享测试</el-button>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>

<script>
import userMedia from './UserMedia.js';
import displayMedia from './DisplayMedia.js';
// import RTCClass from './RTCUtils.js'
import RTCWebSocketClass from './WebSocketUtils'

export default {
  data() {
    return {
      currentMainVideoKey: "mainVideo",
      otherVideoList: ['otherVideo1', 'otherVideo2', 'otherVideo3'],
      // 第一个为摄像头，第二个为屏幕
      localStreamList: [],
      isSwaping: false,
    };
  },
  async mounted() {
  },
  methods: {
    testButton() {
      this.displayStart();
    },
    // 计算中心点位置
    getCenterOfElement(element) {
      if (element) {
        const rect = element.getBoundingClientRect();
        const centerX = rect.left + rect.width / 2;
        const centerY = rect.top + rect.height / 2;
        return { centerX, centerY };
      }
      return null;
    },

    // 获取盒子1相对于盒子2的缩放
    getScale(dom1, dom2) {
      const originalWidth1 = dom1.offsetWidth;
      const originalHeight1 = dom1.offsetHeight;
      const originalWidth2 = dom2.offsetWidth;
      const originalHeight2 = dom2.offsetHeight;
      return `scale(${originalWidth2 / originalWidth1},${originalHeight2 / originalHeight1})`;
    },
    // 应用动画
    applyTransform(dom, x, y, scale) {
      // 动画初始化
      dom.style.transition = 'transform 1s';
      /* 设置变换的原点为中心 */
      dom.style.transformOrigin = 'center';
      // 在下一个事件循环中改变 transform 属性，以确保 transition 属性已经被设置
      this.$nextTick(() => {
        dom.style.transform = `translate(${x}px,${y}px) ${scale}`;
      });
    },
    // 清除动画
    removeTransform(dom) {
      dom.style.transition = '';
      dom.style.transformOrigin = '';
      dom.style.transform = '';
    },
    // 把盒子1和盒子2相互移动
    async swapDivTransform(dom1, dom2, callback) {
      // 创建动画
      let dom1Center = this.getCenterOfElement(dom1);
      let dom2Center = this.getCenterOfElement(dom2);
      this.applyTransform(dom1, dom2Center.centerX - dom1Center.centerX, dom2Center.centerY - dom1Center.centerY, this.getScale(dom1, dom2));
      this.applyTransform(dom2, dom1Center.centerX - dom2Center.centerX, dom1Center.centerY - dom2Center.centerY, this.getScale(dom2, dom1));
      // 等待回调函数结束
      await callback();
      // 清除动画
      this.removeTransform(dom1);
      this.removeTransform(dom2);
    },
    // 节点内容交换
    swapNodes(node1, node2) {
      // 处理class
      node1.classList.remove('mainVideo');
      node1.classList.add('otherVideo');
      node2.classList.remove('otherVideo');
      node2.classList.add('mainVideo');
      let parent1 = node1.parentNode;
      let parent2 = node2.parentNode;
      let cloneNode1 = node1.cloneNode(true);
      let cloneNode2 = node2.cloneNode(true);
      // 替换节点
      parent1.replaceChild(cloneNode2, node1);
      parent2.replaceChild(cloneNode1, node2);
    },
    // 线程休眠，等待动画执行完成
    sleepTread(timeout = 1000) {
      return new Promise((reslove) => {
        setTimeout(reslove, timeout);
      })
    },
    // 是否允许交换
    isAllowSwap(currentMainVideo, newMainVideo) {
      // 当前的主盒子视频流是否为空，为空不允许交换
      if (!currentMainVideo.srcObject || !newMainVideo.srcObject) {
        return false;
      } else if (this.isSwaping) {
        return false;
      } else if (currentMainVideo.srcObject === newMainVideo.srcObject) {
        // 是否点击的是自身
        return false;
      }
      return true;
    },
    // 视频展示盒子交换
    async swapVideos(event) {
      let currentMainVideo = this.$refs[this.currentMainVideoKey];
      let newMainVideo = event.target;
      if (this.isAllowSwap(currentMainVideo, newMainVideo)) {
        // 锁住不允许一直点击
        this.isSwaping = true;
        try {
          let callback = async () => {
            let tempStream = currentMainVideo.srcObject;
            // 交换视频流
            await this.sleepTread(1000);
            currentMainVideo.srcObject = newMainVideo.srcObject;
            newMainVideo.srcObject = tempStream;

          };
          // 展示盒子交换动画
          await this.swapDivTransform(currentMainVideo, newMainVideo, callback);
          // 节点从属父盒子交换(会导致视频流无法加载，不推荐做法)
          // this.swapNodes(currentMainVideo, newMainVideo);
        } catch (error) {
          console.error(error);
        } finally {
          this.isSwaping = false;
        }
      }
    },
    async getLocal() {
      let select = confirm("开启摄像头和语音")
      if (select) {
        // 获取本地流
        let stream = await userMedia.getUserMediaStream()
        // 展示自己的信息在主显示上
        this.$refs.mainVideo.srcObject = stream
        // this.$refs.otherVideo1.srcObject = stream
        this.localStream = stream
      }
      this.rtcWebSocket = new RTCWebSocketClass([this.$refs.otherVideo1, this.$refs.otherVideo2], this.localStream);
    },
    displayStart() {
      // console.log(displayMedia)
      displayMedia.startDisplayMedia(this.$refs.otherVideo2)
    }
  },
};
</script>

<style scoped>
.mainVideo {
  width: 100%;
  max-width: 1080px;
  /* 宽高比为 1:1，即正方形 */
  aspect-ratio: 16 / 9;
  border-radius: 20px;
  box-shadow: 0 4px 8px rgba(0, 123, 255, 0.3);
  overflow: hidden;
}

.otherVideo {
  width: 100%;
  max-width: 400px;
  /* 宽高比为 1:1，即正方形 */
  aspect-ratio: 16 / 9;
  border-radius: 20px;
  box-shadow: 0 4px 8px rgba(0, 123, 255, 0.3);
  overflow: hidden;
}

.transitionInit {
  transition: 'transform 1s';
  /* 设置变换的原点为中心 */
  transform-origin: 'center';
}
</style>